package com.module.lemlin.custom

import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration

class SpacingItemDecoration(
    //列数
    private val nSpan: Int = 1,
    //纵向间隔
    private val vGap: Int = 0,
    //横向间隔
    private val hGap: Int = 0,
    //是否有头布局
    private val isHead: Boolean = false,
    //是否包含边缘
    private val isEdge: Boolean = true
) : ItemDecoration() {

    override fun getItemOffsets(
        outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State
    ) {
        val position: Int = parent.getChildAdapterPosition(view) - if (isHead) 1 else 0
        if (isHead && position < 0)
            return
        val column: Int = position % nSpan
        if (isEdge) {
            outRect.left =
                hGap - column * hGap / nSpan
            outRect.right =
                (column + 1) * hGap / nSpan
            if (position < nSpan) {
                outRect.top = vGap
            }
            outRect.bottom = vGap
        } else {
            outRect.left = column * hGap / nSpan
            outRect.right =
                hGap - (column + 1) * hGap / nSpan
            if (position - 1 >= nSpan) {
                outRect.top = vGap
            }
            outRect.bottom = vGap
        }
    }

}